package com.lingx.web.api.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lingx.bean.TokenBean;
import com.lingx.service.LingxService;
import com.lingx.service.StartupService;
import com.lingx.service.UserService;
import com.lingx.utils.HttpUtils;
import com.lingx.utils.TokenUtils;
import com.lingx.utils.Utils;
import com.lingx.web.api.IApi;
import com.lingx.web.core.urihanlder.KaptchaHandler;
@Component
public class Api8003 extends AbstractApi implements IApi{
	@Resource
	private JdbcTemplate jdbcTemplate;
	@Resource
	private UserService userService;
	@Resource
	private LingxService lingxService;
	@Resource
	private StartupService startupService;
	@Override
	public int getApiCode() {
		return 8003;
	}
	@Override
	public String getApiName() {
		return "用户登陆";
	}
	@Override
	public Map<String, Object> api(Map<String, Object> param) {
		Map<String,Object> ret=IApi.getRetMap(1, "操作成功");
		String account=IApi.getParamString(param, "account", "");
		String password=IApi.getParamString(param, "password", "");
		String verify=IApi.getParamString(param, "verify", "");
		String whiteIps=lingxService.getConfigValue("lingx.login.white.ips", "");
		String ip=IApi.getParamString(param, "X-Real-IP", "");
		
		if(Utils.isNotNull(whiteIps)) {
			if(whiteIps.contains(ip)||",127.0.0.1,localhost,".contains(ip)) {
				
			}else {
				ret.put("code", -91);
				ret.put("message", "登录失败，IP不在白名单之内！");
				return ret;
			}
		}

		if("".equals(account)||"".equals(password)) {
			ret.put("code", -1);
			ret.put("message", "登录失败，参数不可为空！");
			return ret;
		}
		account=account.trim();
		password=password.trim();
		verify=verify.trim();
		boolean isYZM="true".equals(this.lingxService.getConfigValue("lingx.login.yzm.enable", "false"));
		if(isYZM&&!ip.equals(KaptchaHandler.YZM_CACHE.getIfPresent(verify))) {
			//System.out.println(ip +" == "+KaptchaHandler.YZM_CACHE.getIfPresent(verify));
			ret.put("code", -1);
			ret.put("message", "登录失败，验证码无效！");
			return ret;
		}
		boolean b=false;
		int count = -1;
		String sql = "select * from tlingx_user where account=?";// ,pass.replace(" ",
		count = lingxService.queryForInt("select count(*) from tlingx_user where account=?",account);
		if (count == 0) {
			ret.put("code", -1);
			ret.put("message", "登录失败，账号或密码错误！");
			jdbcTemplate.update("insert into tlingx_login_log(userid,ip,message,ts) values(?,?,?,?)",account, ip, "账号或密码错误", Utils.getTime());
			
			return ret;
		}
		count = -1;
		Map<String, Object> map = jdbcTemplate.queryForMap(sql,account.trim());
		if (map != null) {
			if(!"1".equals(map.get("status").toString())) {
				ret.put("code", -1);
				ret.put("message", "登录失败，用户已被禁止登录！");
				return ret;
			}
			String p = map.get("password").toString();
			String r = p.substring(32);
			password = Utils.md5(password)+r;
			b=(password.equals(p));
			if(b){
				this.jdbcTemplate.update("update tlingx_user set login_count=login_count+1,last_login_time=?,last_login_ip=? where account=?",Utils.getTime(),ip,account);
				TokenBean bean=userService.getTokenBean(account);
				System.out.println(JSON.toJSONString(bean));
				String token=TokenUtils.getToken(bean);
				ret.put("id", bean.getUserId());
				ret.put("name", bean.getUserName());
				ret.put("token", token);
				jdbcTemplate.update("insert into tlingx_login_log(userid,ip,message,ts) values(?,?,?,?)",account, ip, "登陆成功", Utils.getTime());
				
			}else {
				ret.put("code", -1);
				ret.put("message", "登录失败，账号或密码错误！");
				jdbcTemplate.update("insert into tlingx_login_log(userid,ip,message,ts) values(?,?,?,?)",account, ip, "账号或密码错误", Utils.getTime());
				
				return ret;
			}
		}
		
		/*
		 new Thread(() -> {
	            try {
	                String result = HttpUtils.get("https://route.showapi.com/20-1?showapi_appid=1158222&showapi_sign=a771b3eb3148482cb6806d2345ef4ce1&ip=" + ip);
	                JSONObject jsonObject = JSON.parseObject(result);
	                if (jsonObject.getInteger("showapi_res_code") == 0) {
	                    JSONObject showapi_res_body = jsonObject.getJSONObject("showapi_res_body");
	                    List<String> areas = new ArrayList<>();
	                    String country = showapi_res_body.getString("country");
	                    if (!"中国".equals(country)) {
	                        areas.add(country);
	                    }
	                    String region = showapi_res_body.getString("region");
	                    if (Utils.isNotNull(region)) {
	                        areas.add(region);
	                    }
	                    String city = showapi_res_body.getString("city");
	                    if (Utils.isNotNull(city)) {
	                        areas.add(city);
	                    }

	                    String areaStr = String.join("-", areas);


	                    jdbcTemplate.update("update tim_user set last_login_ip_area=? where id=?", areaStr, userId);
	                } else {
	                    System.out.println("更新登陆IP归属地错误:" + result);
	                }
	            } catch (Exception ex) {
	                ex.printStackTrace();
	            }
	        }).start();*/
		return ret;
	}

}
